using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Ultimate.DAL.CollectionClasses;
using Ultimate.DAL;
using Ultimate.DAL.HelperClasses;
using Ultimate.DAL.EntityClasses;
using Ultimate.DAL.FactoryClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;

namespace CommunityServerWeb.RegistrationSystem.Controls
{
    public partial class SignUpWizard : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                LoadNBindInitialData();
            }
        }
        
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            string createTeamClick = "ShowNewTeamDetails(this, '" + ddlTeams.ClientID + "', '" + 
                txtNewTeamName.ClientID + "');";
            rdoCreateTeam.Attributes.Add("onclick", createTeamClick);

            string joinTeamClick = "ShowJoinTeamDetails(this, '" + ddlTeams.ClientID + "', '" +
                txtNewTeamName.ClientID + "');";
            rdoJoinTeam.Attributes.Add("onclick", joinTeamClick);

            string startup = "ShowSelectedRegistrationTypeDetails('" + rdoJoinTeam.ClientID +
                "', '" + ddlTeams.ClientID + "', '" +
                txtNewTeamName.ClientID + "');";
            Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowSelectedRegistrationTypeDetails", startup, true);
        }


        private void LoadNBindInitialData()
        {
            int[] usersCurrentLeagueIds = GetUsersCurrentlyJoinedLeagues();

            LeagueCollection leagues = new LeagueCollection();
            PredicateExpression filter = new PredicateExpression();
            filter.Add(PredicateFactory.CompareValue(LeagueFieldIndex.RegistrationOpen, ComparisonOperator.Equal, true));
            filter.AddWithAnd(PredicateFactory.CompareValue(LeagueFieldIndex.Active, ComparisonOperator.Equal, true));
            if (usersCurrentLeagueIds.Length > 0)
            {
                filter.AddWithAnd(PredicateFactory.CompareRange(
                    LeagueFieldIndex.LeagueID, 
                    true, 
                    usersCurrentLeagueIds));
            }


            leagues.GetMulti(filter);

            ddlLeagues.DataTextField = "Name";
            ddlLeagues.DataValueField = "LeagueID";
            ddlLeagues.DataSource = leagues;
            ddlLeagues.DataBind();
        }

        /// <summary>
        /// Gets the ids of the Leagues the current user is already a part of.
        /// </summary>
        /// <returns></returns>
        private int[] GetUsersCurrentlyJoinedLeagues()
        {
            System.Web.Security.MembershipUser mu = System.Web.Security.Membership.GetUser();
            Guid userID = (Guid)mu.ProviderUserKey;

            PredicateExpression filter = new PredicateExpression();
            filter.Add(PredicateFactory.CompareValue(TeamPlayerFieldIndex.UserID, ComparisonOperator.Equal, userID));
            IRelationCollection relations = new RelationCollection();
            relations.Add(TeamEntity.Relations.TeamPlayerEntityUsingTeamID);

            TeamCollection teams = new TeamCollection();
            teams.GetMulti(filter, relations);

            int[] ids = new int[teams.Count];

            for (int i = 0; i < teams.Count; i++)
            {
                ids[i] = teams[i].LeagueID;
            }

            return ids;
        }

        private bool ValidationRegistration()
        {
            bool isValid = false;
            if (rdoJoinTeam.Checked)
            {
                if (ddlTeams.SelectedIndex >= 0)
                {
                    isValid = true;
                }
                else
                {//Display error
                    lblError.Text = "Please select a team to join.";
                }
            }
            else if (rdoCreateTeam.Checked)
            {
                if (txtNewTeamName.Text.Length > 0)
                {
                    isValid = true;
                }
                else
                {//Display error
                    lblError.Text = "Please enter the team name you wish to create.";
                }
            }

            return isValid;
        }
        private void FillConfirmation()
        {
            lblLeagueName.Text = ddlLeagues.SelectedItem.Text;
            
            if(rdoJoinTeam.Checked)
            {
                lblRegistrationType.Text = "with team ";
                lblTeamName.Text = ddlTeams.SelectedItem.Text;

                if (txtFriendName.Text.Length > 0)
                {
                    lblFriendsRequested.Text = " with friends: " + txtFriendName.Text;
                }
            }
            else if(rdoCreateTeam.Checked)
            {
                lblRegistrationType.Text = "as new team ";
                lblTeamName.Text = txtNewTeamName.Text;
            }
        }

        /// <summary>
        /// Set up the registration step for the user.
        /// </summary>
        private void SetupRegistrationStep()
        {
            LeagueEntity league = new LeagueEntity(int.Parse(ddlLeagues.SelectedValue));

            //don't show the create team option if this is an individuals only league.
            if (league.IndividualsOnly)
            {
                rdoCreateTeam.Visible = false;
                txtNewTeamName.Visible = false;

                txtFriendName.Visible = true;
                lblFriendName.Visible = true;

                EnsureIndividuals(league);
            }
            else
            {
                rdoCreateTeam.Visible = true;
                txtNewTeamName.Visible = true;
                
                txtFriendName.Visible = false;
                lblFriendName.Visible = false;
            }

            FillTeamsList(league);
        }
        /// <summary>
        /// Fill the teams drop list with teams from the league.
        /// </summary>
        /// <param name="league"></param>
        private void FillTeamsList(LeagueEntity league)
        {
            ddlTeams.DataSource = league.Team;
            ddlTeams.DataTextField = "TeamName";
            ddlTeams.DataValueField = "TeamID";
            ddlTeams.DataBind();
        }
        /// <summary>
        /// Ensures that there is an indivduals team for the league.
        /// </summary>
        private void EnsureIndividuals(LeagueEntity league)
        {
            //make sure there is an individuals team.            
            IPredicateExpression individualsFilter = new PredicateExpression();
            individualsFilter.Add(PredicateFactory.CompareValue(
                TeamFieldIndex.LeagueID,
                ComparisonOperator.Equal,
                league.LeagueID));
            individualsFilter.AddWithAnd(PredicateFactory.CompareValue(
                TeamFieldIndex.TeamName,
                ComparisonOperator.Equal,
                "Individuals"));
            TeamCollection teams = new TeamCollection();
            if (teams.GetDbCount(individualsFilter) == 0)
            {//create the indivuduals team for this league.
                TeamEntity individuals = new TeamEntity();
                individuals.AmountPaid = league.TeamFee;
                individuals.LeagueID = league.LeagueID;
                individuals.Paid = true;
                individuals.TeamName = "Individuals";
                individuals.Save();
            }
        }
        
        /// <summary>
        /// Setup the wizard steps as people go through them.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Wizard1_ActiveStepChanged(object sender, EventArgs e)
        {
            switch (Wizard1.ActiveStepIndex)
            {
                case 0://first step nothing to do 
                    break;
                    
                case 1://Choose Registration
                    SetupRegistrationStep();
                    break;

                case 2://Confirmation
                    if (ValidationRegistration())
                    {
                        FillConfirmation();
                    }
                    else
                    {//validation failed go back a step
                        Wizard1.ActiveStepIndex = 1;
                    }
                    break;
            }
        }
        /// <summary>
        /// Complete the user's Registration
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
        {
            TeamPlayerEntity teamPlayer = new TeamPlayerEntity();
           if (rdoJoinTeam.Checked)
            {
                teamPlayer.TeamID = Convert.ToInt32(ddlTeams.SelectedValue);
                teamPlayer.RoleID = (int)Ultimate.Roles.Player;
                teamPlayer.FriendsList = txtFriendName.Text;
                //ErrorMessage.Text = "You have been registered in <a href=\"" + this.ResolveUrl("~/RegistrationSystem/league/editleague.aspx?leagueID=" + tpe.Team.LeagueID.ToString()) + "\">" + tpe.Team.League.Name + "</a> on team <a href=\"" + this.ResolveUrl("~/RegistrationSystem/team/editteam.aspx?teamID=" + tpe.TeamID.ToString()) + "\">" + tpe.Team.TeamName + "</a>.";
            }
            else if(rdoCreateTeam.Checked)
            {
                TeamEntity team = new TeamEntity();
                team.LeagueID = Convert.ToInt32(ddlLeagues.SelectedValue);
                team.TeamName = txtNewTeamName.Text;
                team.Save();

                teamPlayer.TeamID = team.TeamID;
                teamPlayer.RoleID = (int)Ultimate.Roles.Captain;
                //ErrorMessage.Text = "You have been registered in <a href=\"" + this.ResolveUrl("~/RegistrationSystem/league/editleague.aspx?leagueID=" + teamPlayer.Team.LeagueID.ToString()) + "\">" + teamPlayer.Team.League.Name + "</a> and you are the captain of <a href=\"" + this.ResolveUrl("~/RegistrationSystem/team/editteam.aspx?teamID=" + teamPlayer.TeamID.ToString()) + "\">" + teamPlayer.Team.TeamName + "</a>.";
            }

            System.Web.Security.MembershipUser mu = System.Web.Security.Membership.GetUser();
            Guid userID = (Guid)mu.ProviderUserKey;

            teamPlayer.UserID = userID;
            teamPlayer.WaiverSigned = true;
            teamPlayer.Save();
        }
    }
}